/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package serversocket;

import com.thoughtworks.xstream.XStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Francisco Gomez
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // TODO code application logic here
            ServerSocket servicio = new ServerSocket(Integer.valueOf(args[0]));
            Socket socketServicio = null;
            
            System.out.println("Servidor Iniciado y listo");
            //esperamos conexion
            int acceso = 0;
            boolean prueba = true;
            while(prueba) {
                
                socketServicio = servicio.accept();
                PrintWriter salida = new PrintWriter(socketServicio.getOutputStream(), true);
                BufferedReader entrada = new BufferedReader(new InputStreamReader(socketServicio.getInputStream()));
                String llego = entrada.readLine();
                try{
                StringTokenizer tokens = new StringTokenizer(llego,".");
                String Nombre = tokens.nextToken();
                String Pass = tokens.nextToken();
                    try {
                        XStream xstream = new XStream();
                        xstream.alias("Persona", Persona.class);
                        BufferedReader in;
                    try {
                         in = new BufferedReader( new FileReader("C:/ListaUsuarios.xml"));
                         String s, s2 = new String();
                         try {
                                acceso = 0;
                                while ((s = in.readLine()) != null && acceso == 0){
                                    if(s.equals("</Persona>")){
                                        s2 += s + "\n";
                                        Persona Usuario = (Persona)xstream.fromXML(s2);
                                        if(Usuario.getNombre().equals(Nombre)){
                                            if(Usuario.getPass().equals(Pass)){
                                                acceso = 1;
                                            }else{
                                                acceso = -1;
                                            }
                                        }
                                        System.out.println(s2);
                                        s2 = "";
                                    }else{
                                        s2 += s + "\n";
                                    }
                                }
                                in.close();
                        } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                        }
                
                
                
                
                
                if(acceso == 1){
                        salida.println("True");
                        System.out.println("El usuario "+Nombre+" ha ingresado al sistema.");
                }else{
                        salida.println("Usuario Invalido");
                }   
                }catch(Exception e){
                        salida.println(e.getMessage());
                        
                }

                
                //Obj
                    

                    } catch (Exception ex) {
                            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
        
    }catch(Exception e){
      //  System.out.print("Ocurrio un error en la carga de archivo de configuración");
        System.out.print(e.getMessage());
    }
                    
                salida.close();
                entrada.close();
                socketServicio.close();

                if(llego.equals("cierrate")) {
                    break;
                }

            }

            
            servicio.close();
            System.out.println("Me apague");
        } catch (IOException ex) {
            System.out.println("Algo se daño:");
            ex.printStackTrace();
        }
    }

}
